package com.bdqn.controller;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo5 {
    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
    DocumentBuilder db;
    Element brandElement=null;

    Document doc;

    {
        try {
             brandElement=doc.createElement("Brand");
            brandElement.setAttribute("name","三星");
            Element typeElement=doc.createElement("Type");
            typeElement.setAttribute("name","NoteX");
            brandElement.appendChild(typeElement);
            Element phoneElement=(Element)doc.getElementsByTagName("PhoneInfo").item(0);
            phoneElement.appendChild(brandElement);
            doc = db.parse("src/信息收藏.xml");
            NodeList list=doc.getElementsByTagName("Brand");
            for (int i=0;i<list.getLength();i++){
                Element brandElement=(Element)list.item(i);
                String brandName=brandElement.getAttribute("name");
                if(brandName.equals("三星")){
                    brandElement.setAttribute("name","SAMSUNG");//修改属性
                }
            }

            TransformerFactory transformerFactory=TransformerFactory.newInstance();
            Transformer transformer=transformerFactory.newTransformer();
            DOMSource domSource=new DOMSource(doc);
            transformer.setOutputProperty(OutputKeys.ENCODING,"gb2312");
            StreamResult result=new StreamResult(new FileOutputStream("src/信息收藏.xml"));
            transformer.transform(domSource,result);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }


}
